package cn.jbolt.codegen.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.XmlUtil;
import cn.jbolt.core.base.config.JBoltConfig;
import com.jfinal.kit.StrKit;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.util.ArrayList;
import java.util.List;

public class ProjectModuleUtil {
    public static List<String> getList(String projectPath){
        if(StrKit.isBlank(projectPath)){
            throw new RuntimeException("Project Path is null");
        }
        String pomXmlPath = FileUtil.normalize(projectPath+"/pom.xml");
        if(!FileUtil.exist(pomXmlPath)){
            throw new RuntimeException("项目的pom.xml文件不存在");
        }
        Document document = XmlUtil.readXML(pomXmlPath);
        if(document == null){
            throw new RuntimeException("项目的pom.xml文件读取异常");
        }
        NodeList modulesNode = document.getElementsByTagName("modules");
        if(modulesNode == null || modulesNode.getLength() == 0){
            throw new RuntimeException("项目的pom.xml文件未读取modules数据");
        }
        NodeList modules = modulesNode.item(0).getChildNodes();
        if(modules == null || modules.getLength() == 0){
            throw new RuntimeException("项目的pom.xml文件未读取modules数据");
        }
        List<String> names = new ArrayList<>();
        int size = modules.getLength();
        Node node;
        String name;
        for(int i=0;i<size;i++){
            node = modules.item(i);
            if(node.getNodeType() == Node.ELEMENT_NODE){
                name = node.getTextContent();
                if(!JBoltConfig.CODE_GEN_MODULES_INCLUDE_JBOLT_MODULES && (name.equals("application") || name.startsWith("jbolt_"))){
                    continue;
                }
                names.add(node.getTextContent());
            }
        }
        return names;
    }
}
